import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

export default function useReportLogic() {
  // 加载状态
  const loading = ref(false);
  // 存储筛选后的数据
  const reportList = ref([]);
  // 分页后的数据
  const paginatedReportList = computed(() => reportList.value);

  // 筛选表单数据
  const filterForm = ref({
    type: "",
    status: "",
    dateRange: [],
  });

  // 举报类型列表
  const reportTypes = [
    { value: "包含虚假信息", label: "包含虚假信息" },
    { value: "冒充官方账号", label: "冒充官方账号" },
    { value: "人身攻击言论", label: "人身攻击言论" },
    { value: "泄露个人隐私", label: "泄露个人隐私" },
    { value: "发布垃圾广告", label: "发布垃圾广告" },
    { value: "仇恨言论", label: "仇恨言论" },
    { value: "侵权内容", label: "侵权内容" },
    { value: "色情信息传播", label: "色情信息传播" },
    { value: "恶意骚扰他人", label: "恶意骚扰他人" },
    { value: "政治敏感内容", label: "政治敏感内容" },
    { value: "无实质证据", label: "无实质证据" },
    { value: "主观判断错误", label: "主观判断错误" },
    { value: "重复举报", label: "重复举报" },
    { value: "刷屏干扰", label: "刷屏干扰" },
    { value: "账号异常活动", label: "账号异常活动" },
    { value: "过期信息误导", label: "过期信息误导" },
    { value: "歧视性言论", label: "歧视性言论" },
    { value: "恶意举报行为", label: "恶意举报行为" },
    { value: "违规医疗广告", label: "违规医疗广告" },
    { value: "泄露商业机密", label: "泄露商业机密" },
  ];

  // 处理状态列表
  const handleStatus = [
    { value: "pending", label: "待处理" },
    // { value: "reviewing", label: "审核中" },
    { value: "resolved", label: "已处理" },
    { value: "rejected", label: "已撤销" },
  ];

  // 选中行的 ID 列表
  const selectedRowKeys = ref([]);
  // 当前页码
  const currentPage = ref(1);
  // 每页条数
  const pageSize = ref(parseInt(localStorage.getItem("reportPageSize")) || 10);
  // 数据总数
  const total = ref(0);

  // 显示详细信息的 Dialog 可见状态
  const dialogVisible = ref(false);
  // 存储举报详细信息
  const reportDetail = ref({
    reportId: "",
    createTime: "",
    reporterName: "",
    status: "",
    reportedObjectName: "",
    reason: "",
    targetType: "", // 新增 targetType 字段
    reportedContent: "", // 确保字段存在
    newsTitle: "", // 确保字段存在
    resolution: "", // 新增 resolution 字段
    mode: "view", // 新增 mode 字段，'view' 表示查看模式，'handle' 表示处理模式
    targetId: "", // 新增字段
  });

  // 获取举报类型标签样式
  const getTypeTagType = (type) => {
    const map = {
      包含虚假信息: "info",
      冒充官方账号: "danger",
      人身攻击言论: "danger",
      泄露个人隐私: "warning",
      发布垃圾广告: "info",
      仇恨言论: "danger",
      侵权内容: "warning",
      色情信息传播: "danger",
      恶意骚扰他人: "danger",
      政治敏感内容: "danger",
      无实质证据: "info",
      主观判断错误: "info",
      重复举报: "info",
      刷屏干扰: "info",
      账号异常活动: "warning",
      过期信息误导: "info",
      歧视性言论: "danger",
      恶意举报行为: "info",
      违规医疗广告: "warning",
      泄露商业机密: "warning",
    };
    return map[type] || "info";
  };

  // 获取状态名称
  const getStatusName = (status) => {
    const item = handleStatus.find((item) => item.value === status);
    return item?.label || "未知";
  };

  // 获取状态标签样式
  const getStatusTagType = (status) => {
    const map = {
      pending: "warning",
      reviewing: "info",
      resolved: "success",
      rejected: "info",
    };
    return map[status] || "info";
  };

  // 处理选中行变化
  const handleSelectionChange = (val) => {
    selectedRowKeys.value = val.map((item) => item.reportId);
  };

  // 查看举报详情
  const handleView = (row) => {
    const detail = {
      reportId: row.reportId,
      createTime: row.createTime,
      reporterName: row.reporterName,
      status: row.status,
      reportedObjectName: row.reportedObjectName,
      reason: row.reason,
      targetType: row.targetType,
      reportedContent: row.reportedContent,
      newsTitle: row.newsTitle,
      resolution: row.resolution,
      targetId: row.targetId, // 新增赋值
    };

    reportDetail.value = detail;
    reportDetail.value.mode = "view";
    dialogVisible.value = true;
  };

  // 提交处理结果
  const handleSubmit = () => {
    if (!reportDetail.value.resolution) {
      ElMessage.error("请输入处理结果");
      return;
    }

    const userId = parseInt(localStorage.getItem("id"));
    axios
      .post("/api/report/handleReport", {
        reportId: reportDetail.value.reportId,
        resolution: reportDetail.value.resolution,
        status: "resolved",
        userId: userId,
      })
      .then((response) => {
        if (response.data.code === 200) {
          ElMessage.success("处理成功");
          dialogVisible.value = false;
          fetchData();
        } else {
          ElMessage.error(response.data.message || "处理失败");
        }
      })
      .catch((error) => {
        console.error("处理失败", error);
        ElMessage.error("处理失败");
      });
  };

  // 撤销处理
  const handleCancel = () => {
    ElMessageBox.confirm("确定要撤销此举报的处理吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const userId = parseInt(localStorage.getItem("id"));
        axios
          .post("/api/report/cancelReport", {
            reportId: reportDetail.value.reportId,
            status: "rejected",
            userId: userId,
          })
          .then((response) => {
            if (response.data.code === 200) {
              ElMessage.success("撤销成功");
              dialogVisible.value = false;
              fetchData();
            } else {
              ElMessage.error(response.data.message || "撤销失败");
            }
          })
          .catch((error) => {
            console.error("撤销失败", error);
            ElMessage.error("撤销失败");
          });
      })
      .catch(() => {
        // 用户取消撤销
      });
  };

  // 创建独立的数据获取方法
  const fetchData = async () => {
    loading.value = true;
    try {
      const params = {
        pageNo: currentPage.value,
        pageSize: pageSize.value,
      };

      // 添加筛选参数
      if (filterForm.value.type) params.reason = filterForm.value.type;
      if (filterForm.value.status) params.status = filterForm.value.status;
      if (filterForm.value.dateRange?.length === 2) {
        params.startDate = filterForm.value.dateRange[0];
        params.endDate = filterForm.value.dateRange[1];
      }

      const response = await axios.get("/api/report/userReport", { params });

      if (response.data.code === 200) {
        reportList.value = response.data.data.list;
        total.value = response.data.data.total;
      }
    } catch (error) {
      console.error("获取数据失败", error);
    } finally {
      loading.value = false;
    }
  };

  // 处理举报
  const handleHandle = (row) => {
    const detail = {
      reportId: row.reportId,
      createTime: row.createTime,
      reporterName: row.reporterName,
      status: row.status,
      reportedObjectName: row.reportedObjectName,
      reason: row.reason,
      targetType: row.targetType,
      reportedContent: row.reportedContent,
      newsTitle: row.newsTitle,
      resolution: row.resolution,
    };

    reportDetail.value = detail;
    reportDetail.value.mode = "handle";
    dialogVisible.value = true;
  };

  // 删除举报
  const handleDelete = (row) => {
    ElMessageBox.confirm("确定要删除此举报信息吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        axios
          .post("/api/report/batchDeleteReport", {
            reportIds: [row.reportId],
          })
          .then((response) => {
            if (response.data.code === 200) {
              ElMessage.success("删除成功");

              fetchData();
            } else {
              ElMessage.error(response.data.message || "删除失败");
            }
          })
          .catch((error) => {
            console.error("删除失败", error);
            ElMessage.error("删除失败");
          });
      })
      .catch(() => {
        // 用户取消撤销
      });
  };

  // 批量删除举报
  const handleBatchDelete = (ids) => {
    ElMessageBox.confirm("确定要删除选中的举报信息吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        axios
          .post("/api/report/batchDeleteReport", {
            reportIds: ids,
          })
          .then((response) => {
            if (response.data.code === 200) {
              ElMessage.success("批量删除成功");
              fetchData();
              selectedRowKeys.value = []; // 清空选中项
            } else {
              ElMessage.error(response.data.message || "批量删除失败");
            }
          })
          .catch((error) => {
            console.error("批量删除失败", error);
            ElMessage.error("批量删除失败");
          });
      })
      .catch(() => {});
  };

  // 筛选数据
  const handleFilter = () => {
    currentPage.value = 1;
    fetchData();
  };

  // 重置筛选条件
  const resetFilter = () => {
    filterForm.value = {
      type: "",
      status: "",
      dateRange: [],
    };
    handleFilter();
  };

  // 处理页码改变
  const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchData();
  };

  // 处理每页条数改变
  const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    localStorage.setItem("reportPageSize", val);
    fetchData();
  };

  // 组件挂载时获取所有数据
  onMounted(() => {
    fetchData();
  });

  return {
    loading,
    reportList,
    paginatedReportList,
    filterForm,
    reportTypes,
    handleStatus,
    selectedRowKeys,
    currentPage,
    pageSize,
    total,
    dialogVisible,
    reportDetail,
    getTypeTagType,
    getStatusName,
    getStatusTagType,
    handleSelectionChange,
    handleView,
    handleSubmit,
    handleCancel,
    fetchData,
    handleHandle,
    handleDelete,
    handleBatchDelete,
    handleFilter,
    resetFilter,
    handleCurrentChange,
    handleSizeChange,
  };
}
